package org.jeecg.modules.generator.controller;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FileUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.modules.generator.entity.*;
import org.jeecg.modules.generator.service.*;
import org.jeecg.modules.generator.utils.CodeGenerateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author yangfeng
 */
@RestController
@RequestMapping(value = "generator/table")
public class SysGenerateTabController {


    @Autowired
    private SysGeneratedTabService sysGeneratedTabService;

    @Autowired
    private SysGenerateTabColumnService sysGenerateTabColumnService;

    @Autowired
    private SysGenerateModuleConfigService systemModuleConfigService;

    @Autowired
    private SysGenerateTemplateService sysGenerateTemplateService;

    @Autowired
    private CodeGenerateUtils codeGenerateUtils;


    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 查询分页数据
     *
     * @return
     */
    @GetMapping(value = "list")
    public Result<IPage<SysGenerateTab>> list(SysGenerateTab sysGenerateTab,
                                              @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                              @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<SysGenerateTab> generateEntityQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(sysGenerateTab.getTableName())) {
            generateEntityQueryWrapper.like("table_name", sysGenerateTab.getTableName());
        }
        if (StringUtils.isNotEmpty(sysGenerateTab.getDataSourceId())) {
            generateEntityQueryWrapper.eq("data_source_id", sysGenerateTab.getDataSourceId());
        }
        IPage<SysGenerateTab> entityIPage = new Page<>(pageNo, pageSize);
        entityIPage = sysGeneratedTabService.page(entityIPage, generateEntityQueryWrapper);
        return Result.ok(entityIPage);
    }

    /**
     * 查询表的列信息
     */
    @GetMapping(value = "column/list")
    public Result<List<SysGenerateTabColumn>> columnList(@RequestParam("tableId")String tableId) {
        List<SysGenerateTabColumn> sysGenerateTabColumnList = sysGenerateTabColumnService.queryByColumnInfoByTbable(tableId);
        return Result.ok(sysGenerateTabColumnList);
    }

    /**
     * 查询表的列信息
     */
    @GetMapping(value = "column/getColumnField")
    public Result getColumnField(@RequestParam("tableName") String tableName) {
        QueryWrapper<SysGenerateTabColumn> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("table_name", tableName);
        List<SysGenerateTabColumn> sysGenerateTabColumnList = sysGenerateTabColumnService.list(queryWrapper);
        List<Map> mapList = new ArrayList<>();
        sysGenerateTabColumnList.forEach(columnClass -> {
            Map<String, String> columnFieldMap = new HashMap<>();
            columnFieldMap.put("value", columnClass.getFieldName());
            columnFieldMap.put("label", columnClass.getColumnComment());
            mapList.add(columnFieldMap);
        });
        return Result.ok(mapList);
    }


    /**
     * 查询字段的配置信息
     */
    @GetMapping(value = "column/queryById")
    public Result<List<SysGenerateFieldInfoEntity>> queryById(String tableId, String fieldName) {
        List<SysGenerateFieldInfoEntity> fieldInfo = sysGenerateTabColumnService.getColumnFileById(tableId,fieldName);
        return Result.ok(fieldInfo);
    }

    /**
     * 查询所有的字典code
     *
     * @return
     */
    @GetMapping(value = "dictCodeList")
    public Result getDictList() {
        return Result.ok(sysBaseAPI.queryAllDict());
    }


    @GetMapping("addTable")
    public Result addTable(@RequestParam("tableName") String tableName, @RequestParam("systemId") String systemId, @RequestParam("dataSourceId") String dataSourceId) {
        return sysGeneratedTabService.addTbleInfo(tableName, systemId, dataSourceId);
    }



    /**
     * 查询表的列信息
     */
    @GetMapping(value = "editTable")
    public ResponseEntity<byte[]> save(SysGenerateTab generateEntity) {
        ResponseEntity<byte[]> responseEntity = null;
        try {
            generateEntity.setCreateTime(DateUtils.getDate());
            List<Map<String,Object>> selectColumnClassList = sysGenerateTabColumnService.queryByFieldItemInfoByTbableId(generateEntity.getId());

            SysGenerateModuleConfig systemModuleConfig = systemModuleConfigService.getById(generateEntity.getSystemId());
            LambdaQueryWrapper<SysGenerateTemplate> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.in(SysGenerateTemplate::getId, systemModuleConfig.getTemplateIds().split(","));
            List<SysGenerateTemplate> sysGenerateTemplateList = sysGenerateTemplateService.list(queryWrapper);

            generateEntity.setColumnClassList(selectColumnClassList);
            String zipPath = codeGenerateUtils.generate(systemModuleConfig, sysGenerateTemplateList, generateEntity);
            QueryWrapper<SysGenerateTab> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("table_name", generateEntity.getTableName());
            generateEntity.setIsGenerated("1");
            sysGeneratedTabService.update(generateEntity, updateWrapper);
            responseEntity = FileUtil.fileDownload(zipPath);
        } catch (Exception e) {
            e.printStackTrace();
            throw new JeecgBootException(e.getMessage());
        }
        return responseEntity;
    }

    /**
     * 属性信息修改保存
     *
     * @param dataMap
     * @return
     */
    @PutMapping(value = "columnSave")
    public Result columnSave(@RequestBody Map<String,String> dataMap) {
        try {
            sysGenerateTabColumnService.columnSave(dataMap);
            return Result.ok("属性修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("属性修改失败！");
        }
    }

    /**
     * 属性信息修改保存
     *
     * @param tableName
     * @return
     */
    @DeleteMapping(value = "delete")
    public Result delete(@RequestParam("id") String tableName) {

        try {
            //删除表信息
            QueryWrapper<SysGenerateTab> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("table_name", tableName);
            sysGeneratedTabService.remove(queryWrapper);
            //删除表的字段信息
            QueryWrapper<SysGenerateTabColumn> sysGenerateTabColumnQueryWrapper = new QueryWrapper<>();
            sysGenerateTabColumnQueryWrapper.eq("table_name", tableName);
            sysGenerateTabColumnService.remove(sysGenerateTabColumnQueryWrapper);
            return Result.ok("删除成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败！");
        }
    }
}
